import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_bilibili/core/extension/int_extension.dart';
import 'package:flutter_bilibili/core/model/space_acc_info_model.dart';
import 'package:flutter_bilibili/ui/pages/home/home_recommend.dart';
import 'package:flutter_bilibili/ui/shared/app_theme.dart';
import 'package:flutter_bilibili/ui/shared/image_assets.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:jverify/jverify.dart';
import '../../../core/event_bus/event_bus.dart';
import '../../widgets/rectangle_checkBox.dart';
import '../live/live.dart';
import '../login/login.dart';
import 'home_initialize_item.dart';

class HYHomeContent extends StatefulWidget {
  const HYHomeContent({Key? key}) : super(key: key);

  @override
  State<HYHomeContent> createState() => _HYHomeContentState();
}

class _HYHomeContentState extends State<HYHomeContent> {
  ///用户头像
  String _userLogo = "";

  /**
   * 极光认证
   * 统一 key - f_result_key
   * 错误码 - f_code_key
   * 回调的提示信息，统一返回 flutter 为 message - f_msg_key
   * 运营商信息 - f_opr_key
   */
  final String f_result_key = "result";
  final String f_code_key = "code";
  final String f_msg_key = "message";
  final String f_opr_key = "operator";

  String _result = "token=";
  var controllerPHone = TextEditingController();
  final Jverify jverify = Jverify();
  String? _token;

  @override
  void initState() {
    ///监听事件总线传来的用户头像链接
    spaceAccInfoEventBus.on<HYSpaceAccInfoModel>().listen((event) {
      setState(() {
        _userLogo = event.face;
      });
    });

    ///极光认证初始化
    initPlatformState();

    ///极光认证sdk初始化
    isInitSuccess();

    ///获取号码认证 Token
    getToken();

    ///预取号
    preLogin();

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    ///DefaultTabController用于tabbar和tabbarView
    return DefaultTabController(
      ///设置几个tabBarItem
      length: tabTitle.length,
      initialIndex: 1,

      ///上划
      child: NestedScrollView(
        headerSliverBuilder: (ctx, innerBoxIsScrolled) {
          return [
            SliverAppBar(
              ///头像
              leading: buildHomeUserIcon(context, _userLogo),

              ///搜索
              title: buildHomeSearch(),

              ///右侧工具栏
              actions: buildHomeActions(),

              ///向上滑动无需停留顶部
              pinned: false,

              floating: false,
              snap: false,
            ),
            SliverAppBar(
              ///设置高度
              toolbarHeight: 40.px,

              ///tabBar
              title: buildHomeTabBar(),

              ///向上滑动需停留顶部
              pinned: true,

              floating: true,
              snap: true,
            ),
          ];
        },

        ///tabBarView
        body: buildHomeTabBarView(),
      ),
    );
  }

  Future<void> initPlatformState() async {
    // 初始化 SDK 之前添加监听
    jverify.addSDKSetupCallBackListener((JVSDKSetupEvent event) {
      print("receive sdk setup call back event :${event.toMap()}");
    });

    jverify.setDebugMode(true); // 打开调试模式
    jverify.setup(
        appKey: "4fedb3342b7faeab82225790", //"你自己应用的 AppKey",
        channel: "devloper-default"); // 初始化sdk,  appKey 和 channel 只对ios设置有效
    if (!mounted) return;

    /// 授权页面点击时间监听
    jverify.addAuthPageEventListener((JVAuthPageEvent event) {
      print("receive auth page event :${event.toMap()}");
    });
  }

  void isInitSuccess() {
    jverify.isInitSuccess().then((map) {
      bool result = map[f_result_key];
      setState(() {
        if (result) {
          _result = "sdk 初始换成功";
        } else {
          _result = "sdk 初始换失败";
        }
      });
    });
  }

  /// 判断当前网络环境是否可以发起认证
  void checkVerifyEnable() {
    jverify.checkVerifyEnable().then((map) {
      bool result = map[f_result_key];
      setState(() {
        if (result) {
          _result = "当前网络环境【支持认证】！";
        } else {
          _result = "当前网络环境【不支持认证】！";
        }
      });
    });
  }

  /// 获取号码认证token
  void getToken() {
    setState(() {
      _showLoading(context);
    });
    jverify.checkVerifyEnable().then((map) {
      bool result = map[f_result_key];
      if (result) {
        jverify.getToken().then((map) {
          int code = map[f_code_key];
          _token = map[f_msg_key];
          String operator = map[f_opr_key];
          setState(() {
            _hideLoading();
            _result = "[$code] message = $_token, operator = $operator";
          });
        });
      } else {
        setState(() {
          _hideLoading();
          _result = "[2016],msg = 当前网络环境不支持认证";
        });
      }
    });
  }

  ///预取号
  void preLogin() {
    setState(() {
      _showLoading(context);
    });
    jverify.checkVerifyEnable().then((map) {
      bool result = map[f_result_key];
      if (result) {
        jverify.preLogin().then((map) {
          print("预取号接口回调：${map.toString()}");
          int code = map[f_code_key];
          String message = map[f_msg_key];
          setState(() {
            _hideLoading();
            _result = "[$code] message = $message";
          });
        });
      } else {
        setState(() {
          _hideLoading();
          _result = "[2016],msg = 当前网络环境不支持认证";
        });
      }
    });
  }

  // /// SDK 请求授权一键登录（弹出版本）
  // void loginAuth() {
  //   setState(() {
  //     _showLoading(context);
  //   });
  //   jverify.checkVerifyEnable().then((map) {
  //     bool result = map[f_result_key];
  //     if (result) {
  //       final screenSize = MediaQuery.of(context).size;
  //       final screenWidth = screenSize.width;
  //       final screenHeight = screenSize.height;
  //       bool isiOS = Platform.isIOS;
  //
  //       JVUIConfig uiConfig = JVUIConfig();
  //       uiConfig.logoHidden = true;
  //       uiConfig.numberColor = Colors.black.value;
  //       uiConfig.numberTextBold = true;
  //       uiConfig.numberSize = HYAppTheme.normalFontSize.toInt();
  //       uiConfig.numFieldOffsetY = 70;
  //       uiConfig.sloganHidden = true;
  //       uiConfig.logBtnOffsetY = 110;
  //       uiConfig.logBtnWidth = (screenWidth - 180).toInt();
  //       uiConfig.needStartAnim = true;
  //       uiConfig.needCloseAnim = true;
  //       uiConfig.privacyCheckboxSize = 13;
  //       uiConfig.privacyTextSize = 10;
  //       uiConfig.privacyOffsetX = 10;
  //       uiConfig.privacyTopOffsetY = 190;
  //       uiConfig.privacyItem = [
  //         JVPrivacy("用户协议、隐私政策", "http://www.baidu.com", separator: "、"),
  //         JVPrivacy("中国移动号码认证系统服务协议", "http://www.baidu.com", separator: "、"),
  //       ];
  //       uiConfig.privacyUnderlineText = false;
  //
  //       //弹框模式
  //       JVPopViewConfig popViewConfig = JVPopViewConfig();
  //       popViewConfig.width = (screenWidth - 140).toInt();
  //       popViewConfig.height = (screenHeight - 450).toInt();
  //
  //       uiConfig.popViewConfig = popViewConfig;
  //
  //       /// 添加自定义的 控件 到授权界面
  //       List<JVCustomWidget> widgetList = [];
  //
  //       const jVerifyHeaderText = "jv_header_text"; // 标识控件 id
  //       JVCustomWidget jVerifyHeaderTextWidget =
  //           JVCustomWidget(jVerifyHeaderText, JVCustomWidgetType.textView);
  //       jVerifyHeaderTextWidget.title = "登录注册解锁更多内容";
  //       jVerifyHeaderTextWidget.top = 25;
  //       jVerifyHeaderTextWidget.width = screenWidth.toInt();
  //       jVerifyHeaderTextWidget.backgroundColor = Colors.transparent.value;
  //       jVerifyHeaderTextWidget.isShowUnderline = true;
  //       jVerifyHeaderTextWidget.titleFont = HYAppTheme.xSmallFontSize;
  //       jVerifyHeaderTextWidget.textAlignment = JVTextAlignmentType.center;
  //       jVerifyHeaderTextWidget.isShowUnderline = false;
  //
  //       const jVerifyOtherLoginText = "jv_other_login_text"; // 标识控件 id
  //       JVCustomWidget jVerifyOtherLoginTextWidget =
  //           JVCustomWidget(jVerifyOtherLoginText, JVCustomWidgetType.textView);
  //       jVerifyOtherLoginTextWidget.title = "其他登录方式";
  //       jVerifyOtherLoginTextWidget.top = 160;
  //       jVerifyOtherLoginTextWidget.width = screenWidth.toInt();
  //       jVerifyOtherLoginTextWidget.backgroundColor = Colors.transparent.value;
  //       jVerifyOtherLoginTextWidget.titleColor =
  //           const Color.fromRGBO(77, 77, 77, 1).value;
  //       jVerifyOtherLoginTextWidget.isShowUnderline = false;
  //       jVerifyOtherLoginTextWidget.titleFont = HYAppTheme.xSmallFontSize;
  //       jVerifyOtherLoginTextWidget.textAlignment = JVTextAlignmentType.center;
  //
  //       jverify.addClikWidgetEventListener(jVerifyOtherLoginText, (eventId) {
  //         print("receive listener - click widget event :$eventId");
  //         if (jVerifyOtherLoginText == eventId) {
  //           print("receive listener - 点击【关闭按钮】");
  //
  //         }
  //       });
  //
  //       const String jVerifyCloseText = "jv_close_button"; // 标识控件 id
  //       JVCustomWidget jVerifyCloseTextWidget =
  //           JVCustomWidget(jVerifyCloseText, JVCustomWidgetType.button);
  //       jVerifyCloseTextWidget.title = "X";
  //       jVerifyCloseTextWidget.titleColor = HYAppTheme.norGrayColor.value;
  //       jVerifyCloseTextWidget.top = 0;
  //       jVerifyCloseTextWidget.width = screenWidth.toInt();
  //       jVerifyCloseTextWidget.isShowUnderline = false;
  //       jVerifyCloseTextWidget.textAlignment = JVTextAlignmentType.right;
  //       jVerifyCloseTextWidget.backgroundColor = Colors.transparent.value;
  //
  //       widgetList.add(jVerifyHeaderTextWidget);
  //       widgetList.add(jVerifyOtherLoginTextWidget);
  //       widgetList.add(jVerifyCloseTextWidget);
  //
  //       /// 步骤 1：调用接口设置 UI
  //       jverify.setCustomAuthorizationView(false, uiConfig,
  //           landscapeConfig: uiConfig, widgets: widgetList);
  //
  //       /// 步骤 2：调用一键登录接口
  //
  //       /// 方式一：使用同步接口 （如果想使用异步接口，则忽略此步骤，看方式二）
  //       /// 先，添加 loginAuthSyncApi 接口回调的监听
  //       jverify.addLoginAuthCallBackListener((event) {
  //         setState(() {
  //           _hideLoading();
  //           _hideLoading();
  //           _result = "监听获取返回数据：[${event.code}] message = ${event.message}";
  //         });
  //         print(
  //             "通过添加监听，获取到 loginAuthSyncApi 接口返回数据，code=${event.code},message = ${event.message},operator = ${event.operator}");
  //       });
  //
  //       /// 再，执行同步的一键登录接口
  //       jverify.loginAuthSyncApi(autoDismiss: true);
  //     } else {
  //       setState(() {
  //         _hideLoading();
  //         _result = "[2016],msg = 当前网络环境不支持认证";
  //       });
  //       /*
  //       /// 方式二：使用异步接口 （如果想使用异步接口，则忽略此步骤，看方式二）
  //       /// 先，执行异步的一键登录接口
  //       jverify.loginAuth(true).then((map) {
  //         /// 再，在回调里获取 loginAuth 接口异步返回数据（如果是通过添加 JVLoginAuthCallBackListener 监听来获取返回数据，则忽略此步骤）
  //         int code = map[f_code_key];
  //         String content = map[f_msg_key];
  //         String operator = map[f_opr_key];
  //         setState(() {
  //          _hideLoading();
  //           _result = "接口异步返回数据：[$code] message = $content";
  //         });
  //         print("通过接口异步返回，获取到 loginAuth 接口返回数据，code=$code,message = $content,operator = $operator");
  //       });
  //       */
  //     }
  //   });
  // }
  /// SDK 请求授权一键登录（界面版本）
  void loginAuth() {
    setState(() {
      _showLoading(context);
    });
    jverify.checkVerifyEnable().then((map) {
      bool result = map[f_result_key];
      if (result) {
        final screenSize = MediaQuery.of(context).size;
        final screenWidth = screenSize.width;
        final screenHeight = screenSize.height;
        bool isiOS = Platform.isIOS;

        JVUIConfig uiConfig = JVUIConfig();
        uiConfig.privacyCheckboxSize = 13;
        uiConfig.privacyTextSize = 10;
        uiConfig.privacyOffsetX = 50;
        uiConfig.privacyTopOffsetY = 350;
        uiConfig.privacyItem = [
          JVPrivacy("用户协议、隐私政策", "http://www.baidu.com", separator: "、"),
          JVPrivacy("中国移动号码认证系统服务协议", "http://www.baidu.com", separator: "、"),
        ];
        uiConfig.privacyUnderlineText = false;

        List<JVCustomWidget> widgetList = [];

        /// 步骤 1：调用接口设置 UI
        jverify.setCustomAuthorizationView(false, uiConfig,
            landscapeConfig: uiConfig, widgets: widgetList);

        /// 步骤 2：调用一键登录接口
        /// 方式一：使用同步接口 （如果想使用异步接口，则忽略此步骤，看方式二）
        /// 先，添加 loginAuthSyncApi 接口回调的监听
        jverify.addLoginAuthCallBackListener((event) {
          setState(() {
            _hideLoading();
            _hideLoading();
            _result = "监听获取返回数据：[${event.code}] message = ${event.message}";
          });
          print(
              "通过添加监听，获取到 loginAuthSyncApi 接口返回数据，code=${event.code},message = ${event.message},operator = ${event.operator}");
        });

        /// 再，执行同步的一键登录接口
        jverify.loginAuthSyncApi(autoDismiss: true);
      } else {
        setState(() {
          _hideLoading();
          _result = "[2016],msg = 当前网络环境不支持认证";
        });
      }
    });
  }

  void _showLoading(BuildContext context) {
    // LoadingDialog.show(context);
  }

  void _hideLoading() {
    // LoadingDialog.hidden();
  }

  ///圆形图标（登录图标
  Widget buildHomeUserIcon(BuildContext context, String userInfo) {
    var _flag = true;
    return Container(
      alignment: Alignment.centerRight,
      child: userInfo.isEmpty
          ? CircleAvatar(
              backgroundColor: Theme.of(context).canvasColor,
              child: TextButton(
                onPressed: () async {
                  SmartDialog.showLoading(
                      maskColor: const Color.fromRGBO(0, 0, 0, .4),
                      builder: (ctx) {
                        return Container(
                          decoration: BoxDecoration(
                              color: const Color.fromRGBO(0, 0, 0, .8),
                              borderRadius:
                                  BorderRadius.all(Radius.circular(8.px))),
                          height: 85.px,
                          width: 85.px,
                          padding: EdgeInsets.all(5.px),
                          child: Column(
                            children: [
                              Image.asset(
                                ImageAssets.ploadingGif,
                                width: 35.px,
                                height: 35.px,
                              ),
                              SizedBox(
                                height: 10.px,
                              ),
                              Text(
                                "正在加载...",
                                style: TextStyle(
                                    color: HYAppTheme.norGrayColor,
                                    fontSize: HYAppTheme.xxSmallFontSize),
                              )
                            ],
                          ),
                        );
                      });
                  await Future.delayed(Duration(seconds: 2)).then((value) {
                    SmartDialog.dismiss();
                    SmartDialog.show(builder: (ctx) {
                      return Card(
                        child: Container(
                          padding: EdgeInsets.all(10.px),
                          height: 290.px,
                          width: 270.px,
                          child: Stack(
                            children: [
                              Container(
                                padding: EdgeInsets.all(15.px),
                                child: Column(
                                  children: [
                                    const Text(
                                      "登录注册解锁更多精彩内容",
                                      style: TextStyle(
                                          color: Colors.black,
                                          fontSize: HYAppTheme.xSmallFontSize),
                                    ),
                                    Container(
                                      padding: EdgeInsets.only(
                                          top: 30.px, bottom: 20.px),
                                      child: const Text(
                                        "183****1731",
                                        style: TextStyle(
                                            fontSize: HYAppTheme.normalFontSize,
                                            color: Colors.black),
                                      ),
                                    ),
                                    TextButton(
                                      style: ButtonStyle(
                                          padding: MaterialStateProperty.all(
                                              EdgeInsets.symmetric(
                                                  vertical: 10.px)),
                                          backgroundColor:
                                              MaterialStateProperty.all(
                                                  HYAppTheme.norTextColors)),
                                      onPressed: () {
                                        ///一键登录
                                        loginAuth();
                                      },
                                      child: Container(
                                        padding: EdgeInsets.symmetric(
                                            vertical: 4.px),
                                        alignment: AlignmentDirectional.center,
                                        width: double.infinity,
                                        child: Text(
                                          "本机号码一键登录",
                                          style: TextStyle(
                                              color: Colors.white,
                                              fontSize:
                                                  HYAppTheme.xSmallFontSize),
                                        ),
                                      ),
                                    ),
                                    Container(
                                      padding: EdgeInsets.only(
                                          top: 15.px, bottom: 20.px),
                                      child: GestureDetector(
                                        onTap: () {
                                          Navigator.of(context).pushNamed(
                                              HYLoginScreen.routeName);
                                          SmartDialog.dismiss();
                                        },
                                        child: Text(
                                          "其他方式登录",
                                          style: TextStyle(
                                              fontSize:
                                                  HYAppTheme.xSmallFontSize,
                                              color: Color.fromRGBO(
                                                  77, 77, 77, 1)),
                                        ),
                                      ),
                                    ),
                                    Row(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Container(
                                          child: RectangleCheckBox(
                                            ///自定义矩形的checkbox
                                            size: 14.px,
                                            checkedColor:
                                                HYAppTheme.norTextColors,
                                            isChecked: _flag,
                                            onTap: (value) {
                                              _flag = value!;
                                            },
                                          ),
                                          padding: EdgeInsets.only(
                                              right: 3.px, top: 3.px),
                                        ),
                                        buildHomeAgreement(),
                                      ],
                                    ),
                                  ],
                                ),
                              ),
                              Positioned(
                                right: 0,
                                top: 0,
                                child: Icon(
                                  Icons.close,
                                  color: HYAppTheme.norGrayColor,
                                  size: 13.px,
                                ),
                              ),
                            ],
                          ),
                        ),
                      );
                    });
                    //未登录情况下
                    // Navigator.of(context).pushNamed(HYLoginScreen.routeName);
                  });
                },
                child: Text(
                  "登录",
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: HYAppTheme.norTextColors,
                    fontSize: HYAppTheme.xxSmallFontSize,
                  ),
                ),
              ),
            )
          : GestureDetector(
              onTap: () {
                ///已经登陆的情况下：发一个index，更改底部导航栏的下标
                mineEventBus.fire(3);
              },
              child: CircleAvatar(
                backgroundImage: NetworkImage(userInfo),
              ),
            ),
    );
  }

  Widget buildHomeAgreement() {
    return const Expanded(
      child: Text.rich(
        TextSpan(
          children: [
            TextSpan(
              text: " 我已经阅读并同意",
              style: TextStyle(
                  color: Colors.grey, fontSize: HYAppTheme.xxxSmallFontSize),
            ),
            TextSpan(
              text: "用户协议、隐私政策",
              style: TextStyle(
                  color: Colors.blue, fontSize: HYAppTheme.xxxSmallFontSize),
            ),
            TextSpan(
              text: "和",
              style: TextStyle(
                  color: Colors.grey, fontSize: HYAppTheme.xxxSmallFontSize),
            ),
            TextSpan(
              text: "中国移动号码认证系列服务协议",
              style: TextStyle(
                  color: Colors.blue, fontSize: HYAppTheme.xxxSmallFontSize),
            ),
            TextSpan(
              text: "，未注册绑定的手机号验证成功后将自动注册",
              style: TextStyle(
                  color: Colors.grey, fontSize: HYAppTheme.xxxSmallFontSize),
            ),
          ],
        ),
      ),
    );
  }

  ///搜索
  Widget buildHomeSearch() {
    return Row(
      children: [
        Expanded(
          child: Container(
            alignment: Alignment.centerLeft,
            child: Container(
                padding:
                    EdgeInsets.only(left: 18.px, top: 10.px, bottom: 10.px),
                child: Image.asset(ImageAssets.searchCustomPNG)),
            height: 35.px,
            decoration: BoxDecoration(
                //圆角
                color: Color.fromRGBO(242, 243, 245, 1),
                borderRadius: BorderRadius.circular(180.px)),
          ),
        ),
      ],
    );
  }

  ///右侧工具栏
  List<Widget> buildHomeActions() {
    return [
      IconButton(
          onPressed: () => print("game"),
          icon: Image.asset(
            ImageAssets.gameCustomPNG,
            width: iconSize,
            height: iconSize,
          )),
      IconButton(
          onPressed: () => print("more"),
          icon: Image.asset(
            ImageAssets.mailCustomPNG,
            width: iconSize,
            height: iconSize,
          )),
    ];
  }

  ///直播、推荐那个几个item的tabbar
  TabBar buildHomeTabBar() {
    return TabBar(
      tabs: tabTitle.map((e) => Tab(text: e)).toList(),
      indicatorColor: HYAppTheme.norTextColors,
      unselectedLabelColor: Color.fromRGBO(95, 95, 95, 1),
      labelColor: HYAppTheme.norTextColors,
      indicatorSize: TabBarIndicatorSize.label,
      labelStyle: TextStyle(fontWeight: FontWeight.bold),
      unselectedLabelStyle: TextStyle(fontWeight: FontWeight.normal),

      ///下划线的厚度
      indicatorWeight: 4.px,
      labelPadding: EdgeInsets.zero,
      indicatorPadding: EdgeInsets.only(bottom: 10.px),
    );
  }

  ///home中主要显示的内容，与tabBar对应
  Widget buildHomeTabBarView() {
    return TabBarView(
      children: tabTitle.map((e) {
        if (e == "直播") {
          return const HYLiveScreen();
        } else if (e == "推荐") {
          return const HYHomeRecommendScreen();
        } else if (e == "动画") {
          return const HYHomeRecommendScreen();
        } else if (e == "影视") {
          return const HYHomeRecommendScreen();
        } else {
          return const HYHomeRecommendScreen();
        }
      }).toList(),
    );
  }
}
